package middlewareorid.engine;

import superwaba.ext.xplat.io.http.HttpStream;
import superwaba.ext.xplat.io.http.URI;
import superwaba.ext.xplat.xml.XmlReadableSocket;
import waba.ui.*;
import waba.util.Vector;

public class HTMLConnect{
	
	private String URL;
	private int maxTry = 3;
	private int timeOut = 180000;
	private String proxyAddress = null;
	private int proxyPort = 0;

	public String getProxyAddress() {
		return proxyAddress;
	}

	public void setProxyAddress(String proxyAddress) {
		this.proxyAddress = proxyAddress;
	}

	public int getProxyPort() {
		return proxyPort;
	}

	public void setProxyPort(int proxyPort) {
		this.proxyPort = proxyPort;
	}

	public HTMLConnect() {
	}

	public String getURLData()
	{
		String res = "";
		String conn = URL;
		HttpStream.Options options = new HttpStream.Options();
		options.readTimeOut = timeOut;
		options.doGet = true;
		options.proxyAddress = proxyAddress;
		options.proxyPort = proxyPort;
		try {
			XmlReadableSocket stream = new XmlReadableSocket(new URI(conn),options);
			if(!stream.isOk()) {
				new MessageBox("Error", "HTTP request error !").popupModal();			
			} else {
				byte[] buffer = new byte[4028];
				int read = 1;
				int nowTry = 0;
				int endHtml = 0;
				res = "";
				int lastRead = 0;
				while (nowTry < maxTry) {
					read = stream.readBytes(buffer, lastRead, buffer.length);
					while (!(read==0)) { 
						lastRead = read;
						read = stream.readBytes(buffer, read-1, buffer.length-read-1);
					}
					res = res + new String(buffer);
					endHtml = res.indexOf("</HTML");
					if (endHtml > 0) nowTry = maxTry;
					nowTry++;
				}
			}
		} catch (Exception e) {
			new MessageBox("Error", "HTTP request error !").popupModal();
		}
		return res;
	}
	
	public Vector getListItem(String data) {	
		Vector result = new Vector();
		int start = data.indexOf("[LST]");
		int end = data.indexOf("[/LST]");
		data = data.substring(start+5, end);

		String datas[] = StringEngine.split(data, "||");
		for (int i = 0; i < datas.length; i++) {
			//Vm.debug("SE : " + datas[i]);
			result.insert(i, datas[i]);
		}

		return result;
	}
   
	public void onEvent(Event event)
	{
	}
	
	public String getURL() {
		return URL;
	}

	public void setURL(String url) {
		URL = url;
	}

	public int getMaxTry() {
		return maxTry;
	}

	public void setMaxTry(int maxTry) {
		this.maxTry = maxTry;
	}

	public int getTimeOut() {
		return timeOut;
	}

	public void setTimeOut(int timeOut) {
		this.timeOut = timeOut;
	}
}
